#!/usr/bin/env python
# -*- coding: utf-8 -*-

import socket
import threading
import re
import signal
import sys
import time
from ifconfig import ifconfig

MCAST_GRP = '224.1.1.1'
MCAST_PORT = 5007


# This class represents the request handler thread
class Caster(threading.Thread):
    # Each thread receives the socket and client address from accept()
    def __init__(self, (sock, ip, port)):
    	self.sock = sock;
        self.ip = ip
        self.port = port

	print self.sock, self.ip, self.port
        threading.Thread.__init__(self)

    # This is where the magic happens
    def run(self):
	while True:
		self.sock.sendto("SERVER:" + self.ip + ":" + self.port, (MCAST_GRP, MCAST_PORT))
		time.sleep(1);


# Keyboard Interrupt handler and cleanup routine
def cleanup(*args):
    print 'Exiting'

    global mcast_sock
    global threads

    # Close the server socket
    mcast_sock.close()
    mcast_sock = None

    sys.exit(0)

def looping(*args):

    global mcast_sock
    global threads

    # Wait for all threads
    for t in threads:
        t.join()

# Catch some signals
signal.signal(signal.SIGINT, cleanup)
signal.signal(signal.SIGTERM, cleanup)

threads = []

print ifconfig('eth0')

mcast_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
mcast_sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)

cast = Caster((mcast_sock, "192.168.1.1", "5060"));
cast.daemon = True;
cast.start();
threads.append(cast);

# The "main" loop
# Accepts connections and fires off threads
#while True:
#    rh = RequestHandler(server_sock.accept())
#    rh.daemon = True
#    rh.start()
#    threads.append(rh)

# Execution never reaches here but this should be the last call
looping()

